package com.select.service.impl;

import com.feign.domain.FileInfo;
import com.feign.util.FileUtil;
import com.select.service.SelectService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SelectServiceImpl implements SelectService {

    private final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    /**
     * 配置文件绑定的硬盘路径
     */
    @Value("${project.path}")
    private String path;

    /**
     * 查询根目录文件
     * @return 根目录文件集合
     */
    @Override
    public List<FileInfo> selectRootPath() {
        File file = new File(path);
        List<File> list = new ArrayList<>(Arrays.asList(file.listFiles()));
        FileUtil.defaultSort(list);
        return FileInfo.filesToFileInfoList(list);

    }

    /**
     * 查询文件夹下的文件
     * @param file 文件对象
     * @return 文件夹下的文件集合
     */
    @Override
    public List<FileInfo> selectFilePath(File file) {
        ArrayList<File> list = new ArrayList<>(Arrays.asList(file.listFiles()));
        FileUtil.defaultSort(list);
        return FileInfo.filesToFileInfoList(list);
    }

    /**
     * 搜索文件
     * @param name 文件名
     * @return 文件集合
     */
    @Override
    public List<FileInfo> selectName(String name,Long size) throws Exception {
        File file = FileUtil.folderExist(path);
        List<File> fileList = FileUtil.searchFileName(file, name);
        threadLocal.set(fileList.size());
        if(fileList.size() >= size){
            fileList = fileList.stream().limit(size).collect(Collectors.toList());
        }
        FileUtil.defaultSort(fileList);
        return FileInfo.filesToFileInfoList(fileList);
    }

    @Override
    public Long getFileTotal() {
        return Long.parseLong(threadLocal.get().toString());
    }

    @Override
    public void removeFileTotal() {
        threadLocal.remove();
    }
}
